<?php
declare(strict_types=1);
namespace App;

// hook event_use.php
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;


class Event extends \Framework\Libs\Event
{


    // hook event_public_start.php

    // hook event_public_end.php

    public function message(Frame $frame)
    {
        if($frame->data=='p'){
            return $this->http_server->push($frame->fd,'p');
        }
        if($frame->data=='c'){
            return $this->http_server->push($frame->fd,'{"c":'.$this->T_Config->get('connection_num','Value').',"r":'.$this->T_Config->get('request_count','Value').'}');
        }
        if(!isset($frame->data[10])){
            return false;
        }

        $star_time = get_ut();

        // hook app_on_message.php

        if(isset($data['cmd'])){
            $data['cmd'] = 'ws_'.strtolower($data['cmd']);
            $this->T_request_stat->incr($data['cmd'], 'count', 1);
            $this->T_request_stat->incr($data['cmd'], 'ms', ms_log($star_time));
        }
    }
    public function open(Request $data)
    {
        // hook event_open.php
        $this->Ws->add_uid_fd(1, $data->fd);
        // hook event_open_end.php
    }
    public function close( $fd,$reactorId)
    {
        // hook event_close.php
        if($this->http_server->isEstablished($fd)){
            $this->Ws->del_fd($fd);
            $this->closeClient($fd);
        }

        // hook event_close_end.php
    }

    public function SHA1withRSA($data)
    {
        // hook event_SHA1withRSA.php
        $key = _SYS('Rsa');
        openssl_sign($data, $signature, $key['touni']);
        return base64_encode($signature);
    }

    public function verifySign($data)
    {
        // hook event_verifySign.php
        $signature = $data['sign'];
        unset($data['sign']);
        $key = _SYS('Rsa');
        if (openssl_verify(xn_json_encode($data), base64_decode($signature), $key['fromuni'])) {
            return true;
        } else {
            return false;
        }
    }


    //发给前端
    public function customerMessage($data, $frame)
    {
        // hook event_customerMessage.php
        $mine = $data['mine'];
        $to = $data['to'];
        if ($to['type'] == 'wechat') {
            if (is_numeric($to['id'])) {
                $open = $this->UserOpen->read(['uid' => $to['id'], 'typeid' => 11]);
                $openid = $open['openid'];
            } else {
                $openid = $to['id'];
            }
            return $this->WechatSdk->send_msg($openid, $mine['content']);
        }
    }

    public function unichat($data, $frame)
    {

        // hook event_unichat.php

    }

    public function chat($data, $frame)
    {
        // hook event_chat.php
    }


    public function Join($data)
    {
        // hook event_join_start.php

        // hook event_join_end.php
    }

    public function Auth($data, $frame)
    {
        //var_dump($data);
        $one = $this->AuthNick->read_one_by_shopid($data["shopid"]);

        $arr = [
            'validateTime' => date('Y-m-d\T00:00:01.6844675+08:00', time() - 86400),
            'expireTime' => date('Y-m-d\T23:59:59', time() - 86400),
            'msg' => "授权未开通\r\n请加李辉老师微信 519681688",
            'nickname'=>base64_encode($data["nickname"]),
            'one' => !empty($one)?true:false,
        ];

        $Auth = $this->StoreProductAuth->read_by_appid($data['appid']);
        if (empty($Auth)) {
            return $arr;
        }

        $nick_id = $this->AuthNick->read_nick_id_by_shopid($data["shopid"]);
        if (empty($nick_id)  && !empty($data["shopid"]))  {
            $opername = explode(":",$data["opername"]);
            if(!isset($opername[1])){
                $opername = explode(':',$data['nickname']);
            }
            // var_dump($opername);
            $nick =  $this->AuthNick->read_by_nickname($opername[0]);
            if(empty($nick['nick_id'])){
                return  $arr;
            }
            $nick_id = $nick['nick_id'];
            if(empty($nick['shopid']) && !empty($data['shopid'])){
                $this->AuthNick->update(['nick_id'=>$nick_id],['shopid'=>$data['shopid']]);
            }
        }
        if(!empty($data['one']) && empty($one)){
            $this->AuthNick->update([$this->AuthNick->index => $nick_id], ['is_one' =>1]);
            $one=1;
        }
        $auth_id = $Auth[$this->StoreProductAuth->index];

        $date = $this->AuthNickAuth->check($auth_id, $nick_id);

        $user = $this->User->read_by_username(trim($data['nickname']));
        if(!empty($user['uid'])){
            $this->bindUid($frame->fd,$user['uid']);
            $this->joinGroup($frame->fd,$data['shopid']);
        }
        if(!empty($data['bizan']) && $data['bizan']=="pkaOogtouPCXkcoDehdEewW2fzD9pNINqPuez7r7yHd_2bMkrCiusIDAue7u87KACEtlnslhgXyEkMsMh3whV1TcSXneDopRvpK6XnDpCWgIfWIRXBEOq_2FxzRDO1E_3d"){
            if(!empty($date['time_out'])){
                $date['time_out']= $date['time_out']>time()?$date['time_out']:time()+604800;
            }else{
                $date= ['time_out'=> time()+604800,'create_at'=>time(),'nickname'=>base64_encode($data["nickname"])];
            }
        }

        if (!empty($date['time_out'])) {
            $arr = [
                'validateTime' => date('Y-m-d\T00:00:01.6844675+08:00', $date['create_at']),
                'expireTime' => date('Y-m-d\T23:59:59', $date['time_out']),
                'nickname'=> base64_encode($data["nickname"]),
                'one' =>!empty($one)?true:false,
                'msg' => time() > $date['time_out'] ? "授权已过期\r\n请加李辉老师微信 519681688" : '授权成功',
            ];
        }
        //var_dump($arr);
        return $arr;
    }

    public function Login($data, $frame)
    {
        var_dump($data);
        // hook event_login_start.php
        $post = [];
        if(!empty($data['data'])){
            $user = $this->User->check_token_ws($data['data']);
            if(!empty($user)){
                $nick_id = $this->User->read_nick_id_by_uid($user['uid']);
                $this->bindUid($frame->fd,$user['uid']);
                $this->joinGroup($frame->fd,$nick_id);
                $post['ok']=true;
            }else{
                $post['ok']=false;
                return $post;
            }
        }else{

            $Auth = $this->StoreProductAuth->read_by_appid($data['appid']);
            if (empty($Auth)) {
                return [];
            }

            $data['nickname']= trim($data['nickname']);
            $user = $this->User->read_by_username($data['nickname']);
            if(empty($user['uid'])){
                $password = mt_rand(10000000, 99999999);
                $salt = mt_rand(100000, 999999);
                $newpwd = md5(md5($password) . $salt);

                $user = [
                    'username' => $data['nickname'],
                    'nickname' => $data['nickname'],
                    'password' => $newpwd,
                    'salt' => $salt,
                    'mobile' => $data['operid'],
                    'parent_uid' => 0,
                    'shop_id' => $data["shopid"],
                    'level_id' => $this->UserLevel->is_default,
                    'gid' => 10001,
                    'create_ymd' => date('Ymd'),
                    'login_at' => time(),
                ];

                $user['uid'] = $this->User->insert($user);
                $user =  $this->User->read_by_uid($user['uid']);

            }elseif(empty($user['shop_id']) && !empty($data['shopid'])){
                $this->User->update(['uid'=>$user['uid']],['shop_id'=>$data['shopid']]);
            }

            $post = [];

            $this->bindUid($frame->fd,$user['uid']);
            $this->joinGroup($frame->fd,$data['shopid']);
            $client = $this->http_server->getClientInfo($frame->fd);
            $long = sprintf("%u", ip2long($client['remote_ip']));
            $post['sid'] = _CONF('cookie_prefixes') . _CONF('session_id');
            $post[$post['sid']] = $this->User->make_exchange_token($user, $data['useragent'], $long);

            $nick_id = $this->AuthNick->read_nick_id_by_shopid($data["shopid"]);
            $opername = explode(":",$data["opername"]);
            if(!isset($opername[1])){
                $opername = explode(":",$data['nickname']);
            }

            $nick = $opername[0];
            if (empty($nick_id)) {
                $AuthNick = $this->AuthNick->read_by_nickname($nick);
                if (!empty($AuthNick[$this->AuthNick->index])) {
                    $nick_id = $AuthNick[$this->AuthNick->index];
                    if (empty($AuthNick['shopid']) && !empty($data["shopid"])) {
                        $this->T_AuthNick->set($data['shopid'],['nick_id'=>$nick_id]);
                        $this->AuthNick->update([$this->AuthNick->index => $nick_id], ['shopid' => $data["shopid"]]);
                    }
                }
            }elseif(!empty($data["shopid"])){
                $one = $this->AuthNick->read_one_by_shopid($data["shopid"]);
                if(!empty($data['one']) && empty($one)){
                    $this->AuthNick->update([$this->AuthNick->index => $nick_id], ['is_one' =>1]);
                }
            }
            $auth_id = $Auth[$this->StoreProductAuth->index];
            $date = $this->AuthNickAuth->check($auth_id, $nick_id);
            if (!empty($date)) {
                $auth =  $this->AuthUser->read(['uid'=>$user['uid']]);
                if(empty($auth['uid'])){
                    $this->AuthUser->insert(['uid'=>$user['uid'],'nick_id'=>$nick_id]);
                }
                $this->AuthNickLogin->insert([
                    'nick_id' => $nick_id,
                    'auth_id' => $auth_id,
                    'uid' => $user['uid'],
                    'ip' => $long,
                    'ymd' => date("Ymd"),
                ]);
            }
        }
        // hook event_login_end.php
        return $post;
    }

    // hook event_end.php
}